function pnmwrite( name, im, raw)
%
%   pnmwrite( name, im, raw ) - write a pnm file
%
%   name    -   file name
%   im      -   image to save - size = nr x nc x ncolors
%   raw     -   boolean - write raw format (default)
%
%   file type (.pbm, .pgm, .ppm) determined from suffix of name
%

    % determine image type
    typ = substr( name, -4 );
    if ( strcmp( typ, '.pbm' ) )
        error( 'pbm not implemented' );
    elseif ( ~ ( strcmp(typ, '.pgm') || strcmp(typ, '.ppm') ) )
        error( sprintf( 'unrecognized pnm type <%s>', typ ) );
    end
    
    % determine raw or ascii
    if ( nargin <= 2 )
        raw = true;
    elseif ( ~isbool( raw ) )
        error( 'raw (arg 3) not boolean' );
    end
    
        
    [file, msg] = fopen( name, "w" );
    if ( file == -1 )
        error( msg );
    end
    
    nr = size(im, 1);
    nc = size(im, 2);
    ncolors = size(im, 3);
    
    % determine pbm, pgm, or ppm
    if ( strcmp( typ, '.pgm' ) )
        if ( ncolors ~= 1 )
            error( 'number of colors is not 1 for .pgm' );
        end
        if ( raw )
            fprintf( file, "P5\n%d %d %d\n", nc, nr, 255 );
            fwrite( file, im', 'uint8' );
        else
            fprintf( file, "P2\n%d %d %d\n", nc, nr, 255 );
            fprintf( file, "%d %d %d %d %d %d %d %d\n", round(im') );
        end
    elseif ( strcmp( typ, '.ppm' ) )
        if ( ncolors ~= 3 )
            error( 'number of colors is not 3 for .ppm' );
        end
        if ( raw )
            fprintf( file, "P6\n%d %d %d\n", nc, nr, 255 );
            rgb = zeros(3*nc, nr);
            rgb(1:3:3*nc,:) = im(:,:,1)';
            rgb(2:3:3*nc,:) = im(:,:,2)';
            rgb(3:3:3*nc,:) = im(:,:,3)';
            fwrite( file, rgb, 'uint8' );
        else
            fprintf( file, "P3\n%d %d %d\n", nc, nr, 255 );
            rgb = zeros(3*nc, nr);
            rgb(1:3:3*nc,:) = im(:,:,1)';
            rgb(2:3:3*nc,:) = im(:,:,2)';
            rgb(3:3:3*nc,:) = im(:,:,3)';
            fprintf( file, "%d %d %d\n", rgb );
        end
    end
    
    fclose(file);

